package com.china08.yxyapi.api.comm.bigfileupload;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTemp;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLessonsTempRepository;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 上传片段文件
 * 
 * @author Json
 *
 */
@CrossOrigin
@RestController
public class BigFileUploadBlockController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BigFileUploadBlockController.class);

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    YxyLessonsTempRepository tempRepository;

    @RequestMapping(value = "/api_yw/comm/bigfile/upload/block", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response, //
            @RequestPart MultipartFile file, @RequestParam(value = "md5", required = true) String md5, // 整个文件的md5
            @RequestParam(value = "chunk", required = false, defaultValue = "0") Integer chunk, // 当前第几片
            @RequestParam(value = "chunks", required = false, defaultValue = "1") Integer chunks, // 一共分了多少片
            @RequestParam(value = "size") Integer size // 文件大小
    ) {
        // 模拟异常
        // if (StringUtils.isNotBlank(md5) &&
        // "fa91b54bcaa35dfbc5d6c23cd247e2b3".equals(md5)) {
        // System.out.println(1 / 0);
        // }

        // 模拟网速慢
        // try {
        // Thread.sleep(1000);
        // } catch (Exception e) {
        // }
        RespModel respModel = new RespModel();
        try {
            String savePath = uploadBasePath + "/temp" + YxyResUtil.getPathMonth() + File.separator + md5;
            // 创建目录
            File sf = new File(savePath);
            if (!sf.exists() || !sf.isDirectory()) {
                FileUtils.forceMkdir(sf);
            }
            String realPath = sf.getPath() + File.separator + chunk;
            FileUtils.writeByteArrayToFile(new File(realPath), file.getBytes());

            // 每次上传单片，保存临时数据
            YxyLessonsTemp temp = new YxyLessonsTemp();
            temp.setMd5(md5);
            temp.setLocation(savePath + File.separator + chunk);
            temp.setChunk(chunk);
            tempRepository.save(temp);
        } catch (Exception e) {
            LOGGER.error("上传文件片段异常:" + e);
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 0 失败 1成功
        public Integer status = 0;
    }

}